<script lang="ts" setup>
import { StorageConst } from '@/constant';
import { DefaultApiUrls, type ResultRelationResource } from '@/openapi-generator';
import storage from '@/storage';
import { message, type UploadChangeParam } from 'ant-design-vue';
import type { FileType } from 'ant-design-vue/es/upload/interface';
import { ref } from 'vue';

interface IProps {
  /**
   * 类型限制
   */
  accept?: string
  /**
   * v-model 单文件使用
   */
  value?: string
  /**
   * 多文件使用
   */
  values?: string[]
}

interface IEmits {
  (e: "update:value", value: string): void
  (e: "update:values", value: string[]): void
}

const emits = defineEmits<IEmits>();
const props = withDefaults(defineProps<IProps>(), {
  value: "",
  values: () => []
});

const token = storage.getItem(StorageConst.Token);
const action = DefaultApiUrls.resourceSingleFileUpload;
const header = { Token: token } as any;
const files = ref([]);
const imageUrl = ref(props.value);
const loading = ref(false);

// 上传之前钩子
const onBeforeUpload = (file: FileType, FileList: FileType[]) => {

}

// 上传变化
const onHandleChange = (info: UploadChangeParam) => {
  if (info.file.status === 'uploading') {
    loading.value = true;
    return;
  }
  if (info.file.status === 'done') {
    const res: ResultRelationResource = info.file.response;
    if (res) {
      loading.value = false;
      if (res.code == 401) {
        message.warn("未登录或登录过期，2秒后跳转登录");
        storage.removeItem(StorageConst.Token);
        setTimeout(() => window.location.href = "/authentication", 2000);
        return
      } else if (res.code != 200) {
        message.error(res.message || "上传失败");
        return
      }
      imageUrl.value = res.data.path;
      emits('update:value', imageUrl.value);
    }
    loading.value = false;
  }
  if (info.file.status === 'error') {
    loading.value = false;
    message.error('upload error');
  }
}
</script>
<script lang="ts">
export default { name: "UploadFile" }
</script>

<template>
  <!-- 文件上传组件 -->
  <section class="upload-file-components">
    <a-upload v-model:file-list="files" list-type="picture-card" 
      :accept="accept"
      :headers="header"
      :show-upload-list="false" 
      :action="action" 
      :before-upload="onBeforeUpload"
      @change="onHandleChange">
      <img class="img-class" v-if="imageUrl" :src="imageUrl" />
      <div v-else>
        <loading-outlined v-if="loading"></loading-outlined>
        <plus-outlined v-else></plus-outlined>
      </div>
    </a-upload>
  </section>
</template>

<style lang="less" scoped>
.img-class {
  width: 100%;
  height: 100%;
}
</style>